package org.example.test.service.impl;

import org.example.test.dal.entity.Category;
import org.example.test.dal.mapper.CategoryMapper;
import org.example.test.model.CategoryModel;
import org.example.test.service.CategoriesService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import java.util.List;

@Component
public class CategoriesServiceImpl implements CategoriesService {

    private static final Logger LOGGER = LoggerFactory.getLogger(CategoriesServiceImpl.class);

    @Autowired
    private CategoryMapper categoryMapper;

    @Override
    public CategoryModel getCategoryById(Long id) {
        LOGGER.info("Fetching category by id: {}", id);
        Category category = categoryMapper.selectByPrimaryKey(id);
        CategoryModel categoryModel = new CategoryModel();
        categoryModel.setId(category.getId());
        categoryModel.setName(category.getName());
        if (category == null) {
            LOGGER.warn("Category with id {} not found", id);
        }
        return categoryModel;
    }

    @Override
    public List<CategoryModel> getAllCategories() {
        LOGGER.info("Fetching all categories");
        return categoryMapper.selectAll();
    }

    @Override
    public void createCategory(CategoryModel categoryModel) {
        LOGGER.info("Creating new category: {}", categoryModel);
        Category category = new Category();
        category.setName(categoryModel.getName());
        categoryMapper.insert(category);
        LOGGER.info("Category created successfully with id: {}", categoryModel.getId());
    }

    @Override
    public void updateCategory(CategoryModel categoryModel) {
        LOGGER.info("Updating category with id: {}", categoryModel.getId());
        Category existingCategory = categoryMapper.selectByPrimaryKey(categoryModel.getId());
        if (existingCategory == null) {
            LOGGER.error("Failed to update category - id {} not found", categoryModel.getId());
            throw new RuntimeException("Category not found");
        }
        Category category = new Category();
        category.setId(categoryModel.getId());
        category.setName(categoryModel.getName());
        categoryMapper.update(category);
        LOGGER.info("Category with id {} updated successfully", categoryModel.getId());
    }

    @Override
    public void deleteCategory(Long id) {
        LOGGER.info("Deleting category with id: {}", id);
        int deletedRows = categoryMapper.deleteByPrimaryKey(id);
        if (deletedRows == 0) {
            LOGGER.warn("Failed to delete category - id {} not found", id);
            throw new RuntimeException("Category not found");
        }
        LOGGER.info("Category with id {} deleted successfully", id);
    }
}
